package com.bw.mvicore.model

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bw.common.utils.LogUtils
import com.bw.mvicore.IIntent
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch

/**
 * @author:created by hahajing
 * 时间：2024/4/22 0022
 * 企鹅号:444511958
 * 描述:
 */
abstract class BaseModel<I:IIntent>:IModel<I>,ViewModel() {
    //用于子类访问修改
    protected val _intents = Channel<I>(Channel.UNLIMITED)
    //对外开发比如在V层发送意图使用
    override val intents: Channel<I>
        get() = _intents

    init {
        handleIntent()
    }

    /**
     * 处理V层发送过来的意图
     */
    abstract fun handleIntent()

    fun generateViewModelScope(method:suspend ()->Unit){
        val coroutineExceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
            LogUtils.e("Model","${throwable.message}")
        }

        viewModelScope.launch(Dispatchers.IO+coroutineExceptionHandler) {
            method()
        }
    }



}